<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="icon" href="/assets/terminal.ico?v=1">
  <title>atx-agent terminal</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/xterm@2.9.2/dist/xterm.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/xterm@2.9.2/dist/addons/fullscreen/fullscreen.min.css">
  <style>
    * {
      margin: 0;
    }
    
    html,
    body {
      height: 100%;
    }
    
    #xterm {
      height: 100%;
      background-color: black;
      padding-left: 5px;
    }
  </style>
</head>

<body>
  <div id="xterm"></div>
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/xterm@2.9.2/dist/xterm.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/xterm@2.9.2/dist/addons/fit/fit.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/xterm@2.9.2/dist/addons/fullscreen/fullscreen.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/cos-jquery-resize@1.1.0/jquery.ba-resize.min.js"></script>
  <script>
    var term;
    var websocket = new WebSocket("ws://" + location.host + "/term");
    websocket.binaryType = "arraybuffer";

    function ab2str(buf) {
      return String.fromCharCode.apply(null, new Uint8Array(buf));
    }
    websocket.onopen = function(evt) {
      term = new Terminal({
        screenKeys: true,
        useStyle: true,
        cursorBlink: true,
      });

      term.on('data', function(data) {
        websocket.send(new TextEncoder().encode("\x00" + data));
      });
      term.on('resize', function(evt) {
        websocket.send(new TextEncoder().encode("\x01" + JSON.stringify({
          cols: evt.cols,
          rows: evt.rows
        })))
      });
      term.on('title', function(title) {
        document.title = title;
      });

      term.open(document.getElementById('xterm'));
      term.fit();
      $("#xterm").resize(function() {
        term.fit()
      })

      websocket.onmessage = function(evt) {
        if (evt.data instanceof ArrayBuffer) {
          term.write(ab2str(evt.data));
        } else {
          alert(evt.data)
        }
      }
      websocket.onclose = function(evt) {
        term.write("Session terminated");
        term.destroy();
      }
      websocket.onerror = function(evt) {
        if (typeof console.log == "function") {
          console.log(evt)
        }
      }
    }
  </script>
</body>

</html>